package com.yang.spingboot.yixincallback.qiangqiang;

import java.util.ArrayList;

/**
 * @author yanwei.yang
 * @date 2022/1/20 18:38
 * @description:
 */
public class DocumentIndex extends ArrayList<IndexEntry> {


    /**
     * 查找或插入字符
     *
     * @param word word
     * @return int
     */
    private int operate(String word) {
        for (int i = 0; i < this.size(); i++) {
            String entryWord = this.get(i).getWord().toUpperCase();
            if (word.toUpperCase().equals(entryWord)) {
                return i;
            } else if (word.toUpperCase().compareTo(entryWord) < 0) {
                IndexEntry ie = new IndexEntry(word);
                this.add(i, ie);
                return i;
            }
        }

        IndexEntry ie = new IndexEntry(word);
        this.add(ie);
        return this.size() - 1;
    }


    public void addWord(String word, int num) {
        this.get(operate(word)).add(num);
    }


    /**
     * 处理文字
     *
     * @param str 文字
     * @param num 行数
     */
    public void operateAllWords(String str, int num) {
        String[] words = str.split("\\W+");
        for (String s : words) {
            if (!"".equals(s)) {
                addWord(s, num);
            }
        }
    }
}
